'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: paginator.py
* @Time: 2025/9/24
* @All Rights Reserve By Brtc
'''
import math
from dataclasses import dataclass
from typing import Any
from flask_wtf import FlaskForm
from wtforms import IntegerField
from wtforms.validators import Optional, NumberRange
from pkg.sqlachemy.sqlalchemy import SQLAlchemy

class PaginatorReq(FlaskForm):
    """分页请求数据、涵盖当前页面、每页条数、如果请求需要携带分页信息可直接继承该类"""
    current_page = IntegerField('current_page', default=1 ,validators=[
        Optional(),
        NumberRange(min=1, max=999, message="页码范围1-999")])
    page_size = IntegerField("page_size", default=10, validators=[
        Optional(),
        NumberRange(min=1, max=50, message="每页数据条数范围1-50")
    ])

@dataclass
class Paginator:
    """分页器"""
    total_page:int =0   #总页数
    total_record:int=0  #总条数
    current_page:int=1  #当前页数
    page_size:int=20    #每页条数

    def __init__(self, db:SQLAlchemy, req:PaginatorReq = None):
        if req is not None:
            self.current_page = req.current_page.data
            self.page_size = req.page_size.data
        self.db = db

    def paginate(self, select)->list[Any]:
        """对传入的查询进行分页处理"""
        #1、调用db.paginate进行数据分页
        p = self.db.paginate(select, page=self.current_page, per_page=self.page_size, error_out=False)
        #2、计算总页数  + 总条数
        self.total_record = p.total
        self.total_page = math.ceil(p.total/self.page_size)
        #3、返回分页的数据
        return p.items

@dataclass
class PageModel:
    list:list[Any]
    paginator:Paginator
